from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractUser
import uuid

class UserProfile(AbstractUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    phone = models.CharField(max_length=20, unique=True, verbose_name='手机号')
    last_login = models.DateTimeField(auto_now=True, verbose_name='最后登录时间')
    is_verified = models.BooleanField(default=False, verbose_name='是否验证')
    
    groups = models.ManyToManyField(
        'auth.Group',
        verbose_name='groups',
        blank=True,
        help_text='The groups this user belongs to.',
        related_name='shop_user_set',
        related_query_name='user',
    )
    user_permissions = models.ManyToManyField(
        'auth.Permission',
        verbose_name='user permissions',
        blank=True,
        help_text='Specific permissions for this user.',
        related_name='shop_user_set',
        related_query_name='user',
    )

    class Meta:
        verbose_name = '用户信息'
        verbose_name_plural = '用户信息'

    def __str__(self):
        return self.username

class Address(models.Model):
    PROVINCE_CHOICES = [
        ('BJ', '北京'),
        ('SH', '上海'),
        ('GD', '广东'),
        # 其他省份...
    ]
    
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='addresses')
    province = models.CharField(max_length=20, choices=PROVINCE_CHOICES, verbose_name='省份')
    city = models.CharField(max_length=50, verbose_name='城市')
    district = models.CharField(max_length=50, verbose_name='区县')
    street = models.CharField(max_length=200, verbose_name='街道地址')
    postal_code = models.CharField(max_length=20, verbose_name='邮政编码')
    is_default = models.BooleanField(default=False, verbose_name='默认地址')
    geo_code = models.CharField(max_length=50, blank=True, verbose_name='地理编码')

    class Meta:
        verbose_name = '用户地址'
        verbose_name_plural = '用户地址'

    def __str__(self):
        return f"{self.province}{self.city}{self.district}{self.street}"

class ThirdPartyAuth(models.Model):
    PLATFORM_CHOICES = [
        ('WX', '微信'),
        ('ALIPAY', '支付宝'),
    ]
    
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='third_party_auths')
    platform = models.CharField(max_length=20, choices=PLATFORM_CHOICES, verbose_name='平台')
    openid = models.CharField(max_length=100, verbose_name='OpenID')
    unionid = models.CharField(max_length=100, blank=True, verbose_name='UnionID')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='绑定时间')

    class Meta:
        verbose_name = '第三方账号'
        verbose_name_plural = '第三方账号'
        unique_together = ('platform', 'openid')

    def __str__(self):
        return f"{self.get_platform_display()}:{self.openid}"

class Role(models.Model):
    name = models.CharField(max_length=50, verbose_name='角色名称')
    description = models.TextField(blank=True, verbose_name='角色描述')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '角色'
        verbose_name_plural = '角色'

    def __str__(self):
        return self.name

class PermissionGroup(models.Model):
    name = models.CharField(max_length=50, verbose_name='权限组名称')
    description = models.TextField(blank=True, verbose_name='权限组描述')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '权限组'
        verbose_name_plural = '权限组'

    def __str__(self):
        return self.name

class Permission(models.Model):
    name = models.CharField(max_length=50, verbose_name='权限名称')
    code = models.CharField(max_length=100, unique=True, verbose_name='权限代码')
    description = models.TextField(blank=True, verbose_name='权限描述')
    group = models.ForeignKey(PermissionGroup, on_delete=models.CASCADE, verbose_name='权限组')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '权限'
        verbose_name_plural = '权限'

    def __str__(self):
        return self.name

class UserRole(models.Model):
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name='用户')
    role = models.ForeignKey(Role, on_delete=models.CASCADE, verbose_name='角色')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '用户角色'
        verbose_name_plural = '用户角色'
        unique_together = ('user', 'role')

    def __str__(self):
        return f"{self.user.username} - {self.role.name}"

class RolePermission(models.Model):
    role = models.ForeignKey(Role, on_delete=models.CASCADE, verbose_name='角色')
    permission = models.ForeignKey(Permission, on_delete=models.CASCADE, verbose_name='权限')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '角色权限'
        verbose_name_plural = '角色权限'
        unique_together = ('role', 'permission')

    def __str__(self):
        return f"{self.role.name} - {self.permission.name}"

from mptt.models import MPTTModel, TreeForeignKey

class Category(MPTTModel):
    name = models.CharField(max_length=100, verbose_name='分类名称')
    description = models.TextField(blank=True, verbose_name='分类描述')
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', verbose_name='父级分类')
    
    class MPTTMeta:
        order_insertion_by = ['name']
        verbose_name = '商品分类'
        verbose_name_plural = '商品分类'

    class Meta:
        unique_together = ('name', 'parent')
        verbose_name = '商品分类'
        verbose_name_plural = '商品分类'

    def __str__(self):
        return self.name

class ProductCategory(models.Model):
    name = models.CharField(max_length=100, verbose_name='产品分类名称')
    slug = models.SlugField(max_length=100, unique=True, verbose_name='URL标识', blank=True, null=True)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, verbose_name='父分类')
    level = models.PositiveIntegerField(default=0, verbose_name='层级')
    description = models.TextField(blank=True, verbose_name='分类描述')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '产品分类'
        verbose_name_plural = '产品分类'

    def __str__(self):
        return self.name

class Product(models.Model):
    STATUS_CHOICES = [
        ('active', '上架'),
        ('inactive', '下架'),
    ]
    
    name = models.CharField(max_length=200, verbose_name='商品名称')
    description = models.TextField(verbose_name='商品描述')
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, verbose_name='商品分类')
    brand = models.CharField(max_length=100, blank=True, verbose_name='品牌')
    model = models.CharField(max_length=100, blank=True, verbose_name='型号')
    attributes = models.JSONField(default=dict, verbose_name='扩展属性')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格', default=0)
    stock = models.IntegerField(default=0, verbose_name='库存')
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='inactive', verbose_name='状态')
    sku = models.CharField(max_length=50, unique=True, verbose_name='SKU编码', default='')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '商品'
        verbose_name_plural = '商品'

class ProductSPU(models.Model):
    STATUS_CHOICES = [
        ('active', '上架'),
        ('inactive', '下架'),
    ]
    
    name = models.CharField(max_length=200, verbose_name='商品名称')
    description = models.TextField(verbose_name='商品描述')
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, verbose_name='商品分类')
    brand = models.CharField(max_length=100, blank=True, verbose_name='品牌')
    model = models.CharField(max_length=100, blank=True, verbose_name='型号')
    attributes = models.JSONField(default=dict, verbose_name='扩展属性')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格', default=0)
    stock = models.IntegerField(default=0, verbose_name='库存')
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='inactive', verbose_name='状态')
    sku = models.CharField(max_length=50, unique=True, verbose_name='SKU编码', default='')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '商品SPU'
        verbose_name_plural = '商品SPU'

    def __str__(self):
        return self.name

class ProductSKU(models.Model):
    spu = models.ForeignKey(ProductSPU, on_delete=models.CASCADE, related_name='skus', verbose_name='关联SPU')
    specifications = models.JSONField(verbose_name='规格参数')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='销售价')
    original_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='原价')
    spec_hash = models.CharField(max_length=64, unique=True, verbose_name='规格哈希')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

class DiscountCampaign(models.Model):
    CAMPAIGN_TYPE_CHOICES = [
        ('PERCENT', '百分比折扣'),
        ('FIXED', '固定金额'),
        ('FREE_SHIPPING', '免运费'),
    ]
    
    name = models.CharField(max_length=100, verbose_name='活动名称')
    description = models.TextField(blank=True, verbose_name='活动描述')
    campaign_type = models.CharField(max_length=20, choices=CAMPAIGN_TYPE_CHOICES, verbose_name='活动类型')
    discount_value = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='折扣值')
    start_time = models.DateTimeField(verbose_name='开始时间')
    end_time = models.DateTimeField(verbose_name='结束时间')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    applicable_products = models.ManyToManyField(ProductSKU, blank=True, verbose_name='适用商品')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '折扣活动'
        verbose_name_plural = '折扣活动'

    def __str__(self):
        return self.name

class ReturnOrder(models.Model):
    STATUS_CHOICES = [
        ('pending', '待处理'),
        ('processing', '处理中'),
        ('completed', '已完成'),
        ('rejected', '已拒绝')
    ]
    
    REASON_CATEGORIES = [
        ('quality', '质量问题'),
        ('wrong_item', '发错货'),
        ('change_mind', '改变主意'),
        ('other', '其他原因')
    ]
    
    order = models.ForeignKey('Order', on_delete=models.CASCADE, verbose_name='关联订单')
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name='用户')
    return_reason = models.TextField(verbose_name='退货原因')
    reason_category = models.CharField(max_length=20, choices=REASON_CATEGORIES, default='other', verbose_name='退货原因分类')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='状态')
    processed_by = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True, related_name='processed_returns', verbose_name='处理人')
    process_time = models.DateTimeField(null=True, blank=True, verbose_name='处理时间')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    refund_time = models.DateTimeField(null=True, blank=True, verbose_name='退款时间')
    shipping_time = models.DateTimeField(null=True, blank=True, verbose_name='退货物流时间')

    class Meta:
        verbose_name = '退货订单'
        verbose_name_plural = '退货订单'
        ordering = ['-created_time']
        indexes = [
            models.Index(fields=['order']),
            models.Index(fields=['status']),
            models.Index(fields=['created_time']),
        ]

    def __str__(self):
        return f"退货订单#{self.id} - {self.order.order_no}"

    def __str__(self):
        return f"{self.spu.name} - {self.specifications}"

class Stock(models.Model):
    sku = models.OneToOneField(ProductSKU, on_delete=models.CASCADE, related_name='stock', verbose_name='关联SKU')
    quantity = models.PositiveIntegerField(default=0, verbose_name='可用库存')
    locked_quantity = models.PositiveIntegerField(default=0, verbose_name='锁定库存')

class Coupon(models.Model):
    code = models.CharField(max_length=50, unique=True, verbose_name='优惠券代码')
    discount_value = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='折扣值')
    valid_from = models.DateTimeField(verbose_name='有效期开始')
    valid_to = models.DateTimeField(verbose_name='有效期结束')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '优惠券'
        verbose_name_plural = '优惠券'

    def __str__(self):
        return self.code

    class Meta:
        verbose_name = '库存'
        verbose_name_plural = '库存'

    def __str__(self):
        return f"{self.sku} - 库存: {self.quantity}"

class StockLog(models.Model):
    OPERATION_CHOICES = [
        ('IN', '入库'),
        ('OUT', '出库'),
        ('LOCK', '锁定'),
        ('UNLOCK', '解锁'),
        ('ADJUST', '调整'),
    ]
    
    sku = models.ForeignKey(ProductSKU, on_delete=models.CASCADE, verbose_name='关联SKU')
    operation = models.CharField(max_length=10, choices=OPERATION_CHOICES, verbose_name='操作类型')
    quantity = models.IntegerField(verbose_name='变更数量')
    before_quantity = models.PositiveIntegerField(verbose_name='变更前库存')
    after_quantity = models.PositiveIntegerField(verbose_name='变更后库存')
    reference_id = models.CharField(max_length=100, blank=True, verbose_name='关联单号')
    operator = models.CharField(max_length=50, verbose_name='操作人')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    note = models.TextField(blank=True, verbose_name='备注')

    class Meta:
        verbose_name = '库存流水'
        verbose_name_plural = '库存流水'

    def __str__(self):
        return f"{self.get_operation_display()} - {self.sku}"

class SystemLog(models.Model):
    ACTION_CHOICES = [
        ('LOGIN', '登录'),
        ('LOGOUT', '登出'),
        ('CREATE', '创建'),
        ('UPDATE', '更新'),
        ('DELETE', '删除'),
    ]
    
    user = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='用户')
    action = models.CharField(max_length=10, choices=ACTION_CHOICES, verbose_name='操作类型')
    content = models.TextField(verbose_name='操作内容')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '系统日志'
        verbose_name_plural = '系统日志'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.get_action_display()} - {self.user.username if self.user else '匿名用户'}"

class Cart(models.Model):
    """购物车模型(MySQL降级存储)"""
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name='用户')
    sku = models.ForeignKey(ProductSKU, on_delete=models.CASCADE, verbose_name='商品SKU')
    quantity = models.PositiveIntegerField(default=1, verbose_name='数量')
    is_selected = models.BooleanField(default=True, verbose_name='是否选中')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '购物车'
        verbose_name_plural = '购物车'
        unique_together = ('user', 'sku')

    def __str__(self):
        return f"{self.user.username}的购物车-{self.sku}"

class Order(models.Model):
    STATUS_CHOICES = [
        ('PENDING', '待支付'),
        ('PAID', '已支付'),
        ('SHIPPED', '已发货'),
        ('COMPLETED', '已完成'),
        ('CANCELLED', '已取消'),
        ('REFUNDED', '已退款'),
    ]
    
    order_no = models.CharField(max_length=64, unique=True, verbose_name='订单编号')
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name='用户')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='PENDING', verbose_name='订单状态')
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='订单总金额')
    shipping_no = models.CharField(max_length=100, blank=True, verbose_name='物流单号')
    address = models.JSONField(verbose_name='收货地址快照')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '订单'
        verbose_name_plural = '订单'
        indexes = [
            models.Index(fields=['user', 'status']),
            models.Index(fields=['order_no']),
        ]

    def __str__(self):
        return f"订单#{self.order_no}"

class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items', verbose_name='关联订单')
    sku = models.ForeignKey(ProductSKU, on_delete=models.PROTECT, verbose_name='商品SKU')
    sku_snapshot = models.JSONField(verbose_name='SKU快照')
    quantity = models.PositiveIntegerField(verbose_name='购买数量')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='成交单价')

    class Meta:
        verbose_name = '订单明细'
        verbose_name_plural = '订单明细'
        unique_together = ('order', 'sku')
        indexes = [
            models.Index(fields=['order', 'sku']),
        ]

    def __str__(self):
        return f"{self.quantity}x {self.sku_snapshot.get('name', '')}"

class Payment(models.Model):
    PAYMENT_CHOICES = [
        ('WECHAT', '微信支付'),
        ('ALIPAY', '支付宝'),
        ('UNIONPAY', '银联支付'),
    ]
    
    STATUS_CHOICES = [
        ('PENDING', '处理中'),
        ('SUCCESS', '支付成功'),
        ('FAILED', '支付失败'),
        ('REFUNDED', '已退款'),
    ]
    
    order = models.ForeignKey(Order, on_delete=models.CASCADE, verbose_name='关联订单')
    payment_no = models.CharField(max_length=64, unique=True, verbose_name='支付流水号')
    payment_method = models.CharField(max_length=20, choices=PAYMENT_CHOICES, verbose_name='支付方式')
    third_party_no = models.CharField(max_length=128, blank=True, verbose_name='第三方流水号')
    amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='支付金额')
    fee = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='手续费')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='PENDING', verbose_name='支付状态')
    callback_time = models.DateTimeField(null=True, blank=True, verbose_name='回调时间')
    settlement_status = models.BooleanField(default=False, verbose_name='结算状态')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '支付流水'
        verbose_name_plural = '支付流水'
        indexes = [
            models.Index(fields=['order']),
            models.Index(fields=['payment_no']),
            models.Index(fields=['third_party_no']),
        ]

    def __str__(self):
        return f"支付#{self.payment_no}"


class MessageTemplate(models.Model):
    name = models.CharField(max_length=100, verbose_name='模板名称')
    content = models.TextField(verbose_name='模板内容')
    variables = models.JSONField(default=list, verbose_name='模板变量')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '消息模板'
        verbose_name_plural = '消息模板'

    def __str__(self):
        return self.name


class PushRecord(models.Model):
    template = models.ForeignKey(MessageTemplate, on_delete=models.CASCADE, verbose_name='关联模板')
    send_time = models.DateTimeField(auto_now_add=True, verbose_name='发送时间')
    open_rate = models.FloatField(default=0, verbose_name='打开率')
    conversion_rate = models.FloatField(default=0, verbose_name='转化率')
    ab_test_group = models.CharField(max_length=20, blank=True, verbose_name='AB测试分组')

    class Meta:
        verbose_name = '推送记录'
        verbose_name_plural = '推送记录'

    def __str__(self):
        return f"{self.template.name} - {self.send_time}"
